import 'dart:io';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../models/auth.dart';
import '../services/api_service.dart';

part 'auth_provider.g.dart';

@riverpod
class AuthState extends _$AuthState {
  final FlutterSecureStorage _storage = const FlutterSecureStorage();
  @override
  Future<Auth?> build() async {
    return _restoreAuthFromStorage();
  }

  Future<void> login(String username, String password) async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      return await _login(username, password);
    });
  }

  Future<void> logout() async {
    await _storage.delete(key: 'access_token');
    await _storage.delete(key: 'refresh_token');
    await _storage.delete(key: 'username');
    await _storage.delete(key: 'uid');
    // 立即设置为“未认证”状态（可选）
    state = const AsyncValue.data(null);
    ref.invalidateSelf();
  }

  Future<void> updateTokens({
    required String accessToken,
    required String refreshToken,
  }) async {
    await _storage.write(key: 'access_token', value: accessToken);
    await _storage.write(key: 'refresh_token', value: refreshToken);
  }

  Future<Auth> _login(String username, String password) async {
    try {
      final apiService = ref.read(apiServiceProvider);
      final response = await apiService.post<Auth>(
        '/auth/login',
        (json) => Auth.fromMap(json as ApiJsonMap),
        body: {'username': username, 'password': password},
        requiresAuth: false,
      );
      if (response.data != null) {
        await _updateAuth(response.data!);
        return response.data!;
      }
      throw HttpException(response.toString());
    } catch (e) {
      rethrow;
    }
  }

  Future<void> _updateAuth(Auth auth) async {
    await _storage.write(key: 'access_token', value: auth.accessToken);
    await _storage.write(key: 'refresh_token', value: auth.refreshToken);
    await _storage.write(key: 'username', value: auth.username);
    await _storage.write(key: 'uid', value: '${auth.id}');
  }

  Future<Auth?> _restoreAuthFromStorage() async {
    final accessToken = await _storage.read(key: 'access_token');
    final refreshToken = await _storage.read(key: 'refresh_token');
    final username = await _storage.read(key: 'username');
    final uid = await _storage.read(key: 'uid');
    if (accessToken != null && refreshToken != null) {
      return Auth(
        id: uid != null ? int.tryParse(uid) : null,
        accessToken: accessToken,
        refreshToken: refreshToken,
        username: username,
      );
    }
    return null; // 暂时不自动登录
  }
}

// 提供只读访问的provider（可选，但推荐）
@riverpod
bool isAuthenticated(IsAuthenticatedRef ref) {
  final auth = ref.watch(authStateProvider).value;
  return auth?.accessToken != null && auth?.refreshToken != null;
}
